<template>
	<view class="bizPage" :style="mainStore.themeColor">
		<status-bar title="任务详情" />
		<view class="head p-re">
			<view class="size32 color-222 bold">{{ applyUserInfo.userName }}提交的{{ process.processName }}</view>
			<view class="size26 color-999 m-top12">{{ applyUserInfo.enterpriseName }}</view>
			<!-- 退回：结束流程；驳回/拒绝：返回上一级或申请人 -->
			<view class="m-top24">
				<view class="size26" style="color: #E95A30;" v-if="process.processStatus == 1">等待{{ currentTask.auditUserInfo[0].userName }}处理</view>
				<view class="size26" style="color: #49C85B;" v-if="process.processStatus == 2">审批通过</view>
				<view class="size26" style="color: #E60012;" v-if="process.processStatus == 3">已驳回</view>
				<view class="size26 color-999" v-if="process.processStatus == 4">已取消</view>
				<view class="size26" style="color: #E60012;" v-if="process.processStatus == 5">已退回</view>
			</view>
			<view class="size26 color-999 m-top48">所在部门</view>
			<view class="size30 color-222 m-top12" v-if="applyUserInfo.dept">{{ applyUserInfo.dept.deptName }}</view>
			<view class="back p-ab" :style="{'--bg-color': bgColor}"></view>
		</view>
		<!-- 表单 -->
		<view class="card" v-if="formData.length">
			<view class="d-flex m-bot24">
				<view class="flex-1 size30 color-222 bold">申请明细：</view>
				<view class="d-flex a-center themeColor" @click="toUrl('/bizPage/task/publish?processInstanceId=' + processInstanceId)"
					v-if="process.processStatus == 3 && process.userId == mainStore.userInfo.userId">
					<text class="iconfont icon-xinjiantiezi size40 m-right6"></text>
					<text class="size30">修改</text>
				</view>
			</view>
			<block v-for="(item,index) in formData" :key="index">
				<view class="m-bot24" v-if="item.value">
					<view class="size26 color-999 m-bot12">{{ item.title }}</view>
					<view class="d-flex a-center" @click="openFile(item.value)" v-if="item.fieldType == 'file'">
						<text class="iconfont icon-fujian size40 themeColor"></text>
						<text class="size30 themeColor p-left10">1</text>
					</view>
					<view class="size30 color-222" v-else>{{ item.value }}</view>
				</view>
			</block>
		</view>
		<view class="card" v-if="auditList.length">
			<view class="size30 color-222 bold m-bot24">审批意见&附件：</view>
			<block v-for="(item,index) in auditList" :key="index">
				<view v-if="index == auditList.length - 1">
					<view class="size30 color-222" v-if="item.taskInfo.comment">{{ item.taskInfo.comment }}</view>
					<block v-if="item.taskInfo.files && item.taskInfo.files.length">
						<choose-file title="" :rawList="item.taskInfo.files" :readonly="true" />
					</block>
				</view>
			</block>
		</view>
		<view class="card">
			<view class="size30 color-222 bold m-bot40">审批流程：</view>
			<view class="step d-flex a-center" v-for="(item,index) in tasks" :key="index">
				<view class="dot m-right26"></view>
				<view class="m-right20">
					<view class="size28 color-222">{{ item.taskInfo.name }}</view>
					<view class="m-top10" v-if="(current < 0 || index <= current) && !item.taskInfo.applyTask">
						<block v-if="item.taskInfo.isPass == null && process.processStatus == 1">
							<view class="size24" style="color: #E95A30;" v-if="approver == 1">待处理</view>
							<view class="size24 color-999" v-else>审批中</view>
						</block>
						<view class="d-flex a-center" v-if="item.taskInfo.isPass == true">
							<view class="size24" style="color: #0B77F0;">已同意</view>
							<view class="size24 color-999" v-if="item.copyUserInfo.length">
								<text>（抄送</text>
								<block v-for="(subItem,subIndex) in item.copyUserInfo" :key="subIndex">
									<text>{{ subItem.userName }}</text>
									<text v-if="subIndex != item.copyUserInfo.length - 1">、</text>
								</block>	
								<text>）</text>
							</view>
						</view>
						<view class="size24" style="color: #E60012;" v-if="item.taskInfo.isPass == false">已驳回</view>
					</view>
				</view>
				<block v-if="item.auditUserInfo.length">
					<view class="flex-1 text-right size24 color-666 m-right20">
						{{ item.auditUserInfo[0].userName }}<block v-if="approver == 1 && index == current">（我）</block>
					</view>
					<image class="avatar" :src="item.auditUserInfo[0].avatar ? imgUrls(item.auditUserInfo[0].avatar) : staticImg + 'noExist.jpg'" mode="aspectFill"></image>
				</block>
			</view>
		</view>
		<!-- 申请人 -->
		<view class="Btn bgwhite flexac size28" @click="handleCancel" v-if="approver == 0 && (process.processStatus == 1 || process.processStatus == 3)">撤销</view>
		<!-- "我"是当前审批人才显示 -->
		<view class="bottom bgwhite" v-if="approver == 1 && process.processStatus == 1">
			<view class="bar d-flex j-sb a-center">
				<view class="text-center" @click="tabClick(item)" v-for="(item,index) in tabList" :key="index">
					<image class="icon m-bot4" :src="staticImg + item.icon" mode="aspectFit"></image>
					<view class="size24 color-222">{{ item.name }}</view>
				</view>
				<view class="btn flexac size28 white" @click="tabClick({name: '同意', type: 'agree'})">同意</view>
			</view>
		</view>
		
		<up-modal :show="showModal" showCancelButton :confirmText="'确认' + name" @cancel="modalCancel" @confirm="modalConfirm">
			<template #default v-if="type == 'agree'">
				<choose-file class="fileList" title="上传附件(可选)" :count="9" @getFile="getFile" />
			</template>
			<template #default v-else>
				<up-textarea v-model="comment" placeholder="原因(选填)"></up-textarea>
			</template>
		</up-modal>
	</view>
</template>

<script setup>
	import { ref, computed } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { useMainStore } from '@/stores/index'
	import { staticImg } from '@/utils/config.js'
	import { toUrl, Toast, imgUrls, Modal, Back, showLoading, hideLoading } from '@/utils/utils.js'
	import Http from '@/utils/request.js'
	import statusBar from '../components/statusBar.vue'
	import chooseFile from '../components/chooseFile.vue'

	const mainStore = useMainStore()
	const bgColor = computed(() => {
		switch (process.value.processStatus){
			case '1':
				return '#FF6600'
			case '2':
				return '#2E9E5B'
			case '3':
				return '#FF0000'
			case '4':
				return '#909399'
			case '5':
				return '#FF0000'
		}
	})
	
	// 0申请人、1当前审批人
	// 已办包括我处理的和我发起的、待办表示需要我审批
	const approver = computed(() => { 
		if(applyUserInfo.value.userId == mainStore.userInfo.userId && state.value == 1) return '0'
		if(currentTask.value && currentTask.value.auditUserInfo[0].userId == mainStore.userInfo.userId && state.value == '0') return '1'
	})
	
	const processInstanceId = ref('') // 流程id
	const state = ref('') // 0待办、1已办
	const applyUserInfo = ref('') // 申请人信息
	const process = ref('') // 流程信息
	const taskId = ref('') // 任务id
	const tasks = ref([]) // 审批流程
	const formData = ref('') // 表单数据
	const current = ref(-1) // 当前审核节点的下标(审完为-1)
	const currentTask = ref('') // 当前任务
	const auditList = ref([]) // 保存所有审批意见及附件
	
	onLoad((e) => {
		if(e.processInstanceId) processInstanceId.value = e.processInstanceId
		if(e.state) state.value = e.state
		getInfo()
	})
	
	onShow(() => {
		// 获取转办人的userId
		let userId = uni.getStorageSync('targetUserId')
		if(type.value == 'transfer' && userId) {
			handleTransfer(userId)
			uni.removeStorageSync('targetUserId')
		}
	})
	
	// 查询流程详情
	const getInfo = () => {
		Http.get({
			url: '/hr/process/findDetail',
			data: {
				processInstanceId: processInstanceId.value
			}
		}).then(res => {
			if(res.code != 0) return Toast(res.msg)
			let result = res.data
			if(!result) return
			applyUserInfo.value = result.applyUserInfo
			process.value = result.process
			taskId.value = result.taskId
			tasks.value = result.tasks || []
			formData.value = result.processFormFieldInfos || []
			// isPass：true通过、false拒绝、null未审核
			current.value = tasks.value.findIndex(item => item.taskInfo.isPass == null)
			if(current.value > -1) currentTask.value = tasks.value[current.value]
			getDepts()

			formData.value.forEach(item => {
				if(item.fieldType == 'post' && item.postType == 'user') {
					findUser(item.value).then(name => {
						item.value = name
					})
				}
			})

			auditList.value = tasks.value.filter(item => item.taskInfo.comment || (item.taskInfo.files && item.taskInfo.files.length))
		})
	}
	
	const tabList = ref([
		// { name: '文书', icon: 'task_ws.png', type: 'document' },
		// { name: '附件', icon: 'task_fj.png', type: 'attachment' },
		{ name: '转办', icon: 'task_zb.png', type: 'transfer' },
		{ name: '退回', icon: 'task_th.png', type: 'return' },
		{ name: '拒绝', icon: 'task_jj.png', type: 'refuse' }
	])
	const type = ref('') // 当前操作标识
	const name = ref('')
	const showModal = ref(false)
	const comment = ref('')
	const files = ref([])
	
	const tabClick = (item) => {
		type.value = item.type 
		name.value = item.name
		if(item.type == 'transfer') toUrl('/bizPage/task/selectList?title=转交')
		if(item.type == 'return') showModal.value = true
		if(item.type == 'refuse') showModal.value = true
		if(item.type == 'agree') showModal.value = true
	}

	const modalCancel = () => {
		showModal.value = false
		comment.value = ''
		files.value = []
	}
	
	const modalConfirm = () => {
		if(type.value == 'return') handleAudit({refuse: true, isPass: false})
		if(type.value == 'refuse') handleAudit({isPass: false}) 
		if(type.value == 'agree') handleAudit({isPass: true})
	}

	const getFile = ({list}) => {
		files.value = list
	}

	// 审批
	const handleAudit = async (payload) => {
		if(payload.name) {
			let result = await Modal(`确定${payload.name}吗？`)
			if(!result) return
		}
		let params = {
			processInstanceId: processInstanceId.value,
			auditUserId: mainStore.userInfo.userId,
			auditUserName: mainStore.userInfo.userName
		}
		if(payload.isPass != undefined) params.isPass = payload.isPass
		if(payload.refuse != undefined) params.refuse = payload.refuse
		if(comment.value) params.comment = comment.value
		if(files.value.length) params.files = files.value
		
		Http.post({
			url: '/hr/process/audit',
			data: params
		}).then(res => {
			Toast(res.msg)
			if(res.code != 0) return
			getInfo()
			showModal.value = false
			comment.value = ''
		})
	}

    // 转办
	const handleTransfer = (targetUserId) => {
		Http.post({
			url: '/hr/process/transferTask',
			data: {
				taskId: taskId.value,
				targetUserId
			},
			Typejson: false
		}).then(res => {
			Toast(res.msg)
			if(res.code == 0) getInfo()
		})
	}

	// 撤销
	const handleCancel = async () => {
		let result = await Modal('确定撤销吗？')
		if(!result) return
		Http.post({
			url: '/hr/process/cancel',
			data: {
				processInstanceId: processInstanceId.value
			}
		}).then(res => {
			if(res.code != 0) return Toast(res.msg)
			Back()
		})
	}
	
	// 打开附件
	const openFile = (url) => {
        if(isImg(url)) {
            uni.previewImage({
				urls: [imgUrls(url)]
			})
            return 
        }
        showLoading()
		uni.downloadFile({
			url,
			success(res) {
				uni.openDocument({
					filePath: res.tempFilePath,
					complete() {
						hideLoading()
					}
				})
			},
            fail() {
                hideLoading()
            }
		})
    }

	const isImg = (url) => {
		let suffix = url.slice(url.lastIndexOf('.') + 1)
		let all = ['png','jpg','jpeg','gif','webp','bmp']
        return all.includes(suffix.toLowerCase())
	}
	
	// 部门
	const deptList = ref([])
	const getDepts = () => {
		Http.get({
			url: '/hr/getDeptList'
		}).then(res => {
			if(res.code != 0) return
			deptList.value = res.data || []
			formData.value.forEach(item => {
				if(item.fieldType == 'post' && item.postType == 'department') {
					let result = deptList.value.find(obj => obj.deptId == item.value)
					if(result) item.value = result.deptName
				}
			})
		})
	}

	// 查询员工信息
	const findUser = (userId) => {
		return new Promise(resolve => {
			Http.get({
				url: '/hr/process/findEmployeeInfoByUserId',
				data: {
					userId,
					name: ''
				}
			}).then(res => {
				if(res.code == 0 && res.data) resolve(res.data.name)
			})
		})
	}
</script>

<style lang="scss" scoped>
	.bizPage {
		padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
	}
	.head {
		padding: 50rpx;
		.back {
			width: 100%;
			height: 148rpx;
			background: linear-gradient(180deg, var(--bg-color), #FFFFFF);
			opacity: 0.07;
			top: 0;
			left: 0;
		}
	} 
	.card {
		width: 710rpx;
		background: #F9F9F9;
		border-radius: 20rpx;
		padding: 30rpx;
		margin: 0 auto 20rpx;
	}
	.step:not(:last-child) {
		margin-bottom: 60rpx;
		position: relative;
		&::after {
			content: '';
			width: 1rpx;
			height: 80rpx;
			background: #CDCDCD;
			position: absolute;
			left: 5rpx;
			transform: translateX(-50%);
			bottom: -70rpx;
		}
	}
	.dot {
		width: 10rpx;
		height: 10rpx;
		background: #CDCDCD;
		border-radius: 50%;
	}
	.avatar {
		width: 66rpx;
		height: 66rpx;
		border-radius: 10rpx;
	}
	.Btn {
		width: 690rpx;
		height: 80rpx;
		border: 1rpx solid v-bind('mainStore.color');
		border-radius: 20rpx;
		color: v-bind('mainStore.color');
		position: fixed;
		bottom: calc(20rpx + constant(safe-area-inset-bottom));
		bottom: calc(20rpx + env(safe-area-inset-bottom));
		left: 30rpx;
		z-index: 1;
	}
	.bottom {
		width: 100%;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 1;
		.bar {
			height: 100rpx;
			padding: 0 50rpx;
			border-top: 1rpx solid #dadbde;
			.icon {
				width: 34rpx;
				height: 34rpx;
			}
			.btn {
				width: 264rpx;
				height: 80rpx;
				background: v-bind('mainStore.color');
				border-radius: 40rpx;
			}
		}
	}
	::v-deep .u-modal .u-line {
		height: auto !important;
	}
	.fileList {
		width: 100%;
		min-height: 200rpx;
	}
</style>
